<template>
    <div class="app-container">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            label-width="68px"
        >
            <el-form-item label="课件名" prop="varName">
                <el-input
                    v-model="queryParams.varName"
                    placeholder="请输入"
                    clearable
                    size="small"
                />
            </el-form-item>
            <el-form-item label="课件类型" prop="varType">
                <el-select v-model="queryParams.varType" style="width:100%;">
                    <el-option
                        v-for="dict in fileTypeOptions"
                        :key="dict.dictValue"
                        :label="dict.dictLabel"
                        :value="dict.dictValue"
                    />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button
                    type="primary"
                    icon="el-icon-search"
                    size="mini"
                    @click="handleQuery"
                    >搜索</el-button
                >
                <el-button
                    icon="el-icon-refresh"
                    size="mini"
                    @click="resetQuery"
                    >重置</el-button
                >
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    icon="el-icon-plus"
                    size="mini"
                    @click="handleAdd"
                    v-hasPermi="['system:attachment:add']"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    :disabled="multiple"
                    @click="handleDelete"
                    v-hasPermi="['system:attachment:remove']"
                    >删除</el-button
                >
            </el-col>
        </el-row>

        <el-table
            v-loading="loading"
            :data="attachmentList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                width="55"
                align="center"
                :selectable="checkboxSelect"
            />
            <el-table-column label="课件名" align="center" prop="varName" />
            <el-table-column label="课件类型" align="center" prop="varType" />
            <el-table-column
                label="适用行业"
                align="center"
                prop="varIndustry"
            />
            <el-table-column label="课件状态" align="center" prop="chrValid" />
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="preview(scope.row)"
                        >预览</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="handleUpdate(scope.row)"
                        v-hasPermi="['system:question:edit']"
                        v-if="ancestors.length <= scope.row.intPid.length"
                        >修改</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-if="ancestors.length <= scope.row.intPid.length"
                        v-hasPermi="['system:attachment:remove']"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />

        <!-- 添加或修改附件管理对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
            :before-close="closeDialog"
        >
            <el-form ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="课件名" prop="varName">
                    <el-input
                        placeholder="请输入课件名"
                        v-model="form.varName"
                    />
                </el-form-item>
                <el-form-item label="课件类型" prop="varType">
                    <el-select
                        v-model="form.varType"
                        style="width:100%;"
                        @change="fileTypeChange"
                    >
                        <el-option
                            v-for="dict in fileTypeOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="课件上传" prop="varFid">
                    <el-upload
                        class="upload-demo"
                        action=""
                        :http-request="myUpload"
                        :headers="upload.headers"
                        :on-error="uploadError"
                        :on-change="handleFileChange"
                        :file-list="fileList"
                        :on-remove="removeFile"
                        :before-upload="beforeUpload"
                        multiple
                        :disabled="form.varType === ''"
                        ref="upload"
                        :limit="limitImgNumber"
                        :class="{ hideAdd: uploadDisabled }"
                    >
                        <el-button
                            size="small"
                            type="primary"
                            @click="beforeSelectFile"
                            >点击上传</el-button
                        >
                        <div slot="tip" class="el-upload__tip">
                            <p class="tip">
                                上传的文件格式只能是
                                {{ this.uploadFileType.join("，") }} 格式
                            </p>
                            <p class="tip">
                                视频文件， 且不超过200MB，文件类型不能大于30MB，
                                图片文件不能大于 10MB
                            </p>
                        </div>
                    </el-upload>
                </el-form-item>
                <el-form-item label="适用行业" prop="varIndustry">
                    <el-select
                        v-model="form.varIndustry"
                        placeholder="请选择"
                        :style="{ width: '100%' }"
                    >
                        <el-option
                            v-for="item in varIndustryOptions"
                            :key="item.dictValue"
                            :label="item.dictLabel"
                            :value="item.dictValue"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
        <preview
            :previewUrl="previewUrl"
            :previewVarExt="previewVarExt"
            v-model="showPreview"
        />
    </div>
</template>

<script>
import { listAttachment, getAttachment, delAttachment, addAttachment, updateAttachment, exportAttachment } from "@/api/system/attachment";
import { getToken } from "@/utils/auth";
import OSS from 'ali-oss'
import preview from '@/components/preview'
export default {
    name: "Attachment",
    components: {
        preview
    },
    data () {
        return {
            uploadDisabled: false,
            limitImgNumber: 1,
            upload: {
                // 是否显示弹出层（用户导入）
                open: false,
                // 弹出层标题（用户导入）
                title: "",
                // 是否禁用上传
                isUploading: false,
                // 是否更新已经存在的用户数据
                updateSupport: 0,
                // 设置上传的请求头部
                headers: { Authorization: "Bearer " + getToken() },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + "/common/upload",
            },
            fileList: [],
            // 遮罩层
            loading: true,
            // 选中数组
            ids: [],
            deleteNames: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 总条数
            total: 0,
            ancestors: '',
            // 附件管理表格数据
            attachmentList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                varName: undefined,
                varType: undefined,
            },
            // 表单参数
            form: {
                varName: '', // 附件名称  （必填）
                varFid: '',  // 文件id  （必填）
                varType: '', // 文件类型
                varLocalName: '', // 原始名称   （必填）
                varExt: '',  // 文件后缀   （必填）
                varIndustry: '' // 行业   （必填）
            },
            // 表单校验
            rules: {
                varName: [
                    { required: true, message: '请输入课件名', trigger: ['blur', 'change'] }
                ],
                varFid: [
                    { required: true, message: '请上传课件', trigger: ['blur', 'change'] }
                ],
                varType: [
                    { required: true, message: '请选择文件类型', trigger: ['blur', 'change'] }
                ],
                varIndustry: [
                    { required: true, message: '请选择适用行业', trigger: ['blur', 'change'] }
                ]
            },
            fileTypeOptions: [],
            varIndustryOptions: [], // 适用行业
            fileSize: 0,
            uploadLoading: null,
            showPreview: false,
            previewUrl: '',
            previewVarExt: '',
            uploadFileType: ['mp4', 'word', 'ppt', 'pdf',
                'jpg', 'png', 'bmp', 'mp3'],
            beforeModifiFileName: '',
            deleteFileName: '',
            deleteFileNames: [],
            ossClient: null
        };
    },
    created () {
        this.ossClient = new OSS({
            // region以杭州为例（oss-cn-hangzhou），其他region按实际情况填写。
            region: 'oss-cn-beijing',
            // 阿里云主账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM账号进行API访问或日常运维，请登录RAM控制台创建RAM账号。
            accessKeyId: 'LTAI4G2AAkFNWgjQjTJsvf54',
            accessKeySecret: 'felrC80biKjDjnneY6p7IN9e1laqaV',
            bucket: 'bu-testdata'
        });
        this.getDicts("var_type").then(response => {
            this.fileTypeOptions = response.data;
        });
        this.getDicts("var_industry").then(response => {
            this.varIndustryOptions = response.data;
        });
        this.getList();
    },
    methods: {
        checkboxSelect (row) {
            return this.ancestors.length <= row.intPid.length
        },
        fileTypeChange (val) {
            switch (val) {
                case '1':
                    this.uploadFileType = ['mp4']
                    break;
                case '2':
                    this.uploadFileType = ['doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'pdf']
                    break;
                case '3':
                    this.uploadFileType = ['mp3']
                    break;
                case '4':
                    this.uploadFileType = ['jpg', 'png', 'bmp']
                    break;
                default:
                    break;
            }
        },
        closeDialog (done) {
            this.$refs.upload.clearFiles()
            this.deleteFile(this.deleteFileName)
            done()
        },
        dataFormat (val, options) {
            for (let i = 0; i < this[options].length; i++) {
                if (val == this[options][i].dictLabel) {
                    return this[options][i].dictValue
                }
            }
            return val
        },
        removeFile (file, fileList) {
            if (file.status === "success") {
                if (file.varFid) {
                    this.deleteFile(file.varFid)
                } else {
                    const arr = file.name.split('.')
                    const localName = arr[arr.length - 1]
                    this.deleteFile(`${file.uid}.${localName}`)
                }
            }
            this.form.varLocalName = ''
            this.form.varExt = ''
            this.form.varFid = ''
            this.handleFileChange(file, fileList)
        },
        handleFileChange (file, fileList) {
            this.uploadDisabled = fileList.length >= this.limitImgNumber;
        },

        beforeUpload (file) {
            var fileType = file.name.substring(file.name.lastIndexOf('.') + 1).toLocaleLowerCase()
            this.fileSize = file.size
            return this.verifyFileFormat(fileType, true)
        },
        beforeSelectFile () {
            if (this.form.varType === '') {
                this.$message({
                    message: '请选择文件类型!',
                    type: 'warning'
                });
            }
        },
        verifyFileFormat (fileType, showUploadLoading) {
            var regVideo = ['mp4']
            var regFile = ['doc', 'xls', 'ppt', 'docx', 'xlsx', 'pptx', 'pdf']
            var regImg = ['jpg', 'png', 'bmp']
            var regAudio = ['mp3']
            const isLt2M = this.fileSize / 1024 / 1024
            if (this.form.varType == '1' || this.form.varType === '视频') {
                if (regVideo.indexOf(fileType) === -1) {
                    this.$message({
                        message: '视频文件只能上传mp4格式文件!',
                        type: 'warning'
                    });
                    return false
                } else if (isLt2M > 200) {
                    this.$message({
                        message: '视频文件不能大于 200MB!',
                        type: 'warning'
                    });
                    return false
                }
            } else if (this.form.varType == '2' || this.form.varType == '文档') {
                if (regFile.indexOf(fileType) === -1) {
                    this.$message({
                        message: `文件类型只能上传${regFile.join(',')}格式文件!`,
                        type: 'warning'
                    });
                    return false
                } else if (isLt2M > 30) {
                    this.$message({
                        message: '文件类型不能大于 30MB!',
                        type: 'warning'
                    });
                    return false
                }
            } else if (this.form.varType == '3' || this.form.varType == '音频') {
                if (regAudio.indexOf(fileType) === -1) {
                    this.$message({
                        message: `音频只能上传mp3格式文件!`,
                        type: 'warning'
                    });
                    return false
                } else if (isLt2M > 200) {
                    this.$message({
                        message: '音频文件不能大于 200MB!',
                        type: 'warning'
                    });
                    return false
                }
            } else {
                if (regImg.indexOf(fileType) === -1) {
                    this.$message({
                        message: `图片只能上传jpg, png, bmp格式文件!`,
                        type: 'warning'
                    });
                    return false
                } else if (isLt2M > 200) {
                    this.$message({
                        message: '图片不能大于 10MB!',
                        type: 'warning'
                    });
                    return false
                }
            }
            // if (isLt2M > 50) {
            //     this.$message({
            //         message: `上传文件较大，正在为您加速上传，请您耐心等候!`,
            //         type: 'success'
            //     });
            // }
            if (showUploadLoading) {
                this.uploadLoading = this.$loading({
                    lock: true,
                    text: "上传文件较大，正在为您加速上传，请您耐心等候!",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)"
                });
            }
            return true
        },
        async myUpload (content) {
            /**
             * cnpm install ali-oss
             * 配置本地测试vue虚拟域名房屋内
             * 现在oss跨域配置的地址为 activate.navicat.com
             * https://blog.csdn.net/Snow_xueY/article/details/57086793  前端设置vue虚拟域名访问  mac
             * C:\Windows\System32\drivers\etc文件夹中的hosts文件，在末尾添加127.0.0.1 www.local.com（你的自定义域名） windows
             */

            // 支持File对象、Blob数据以及OSS Buffer。
            const data = content.file;
            // 文件id 生成uuid上传成功以后这个字段传给后台保存(替换之前的url) 例如 277626626662.MP4
            let arr = content.file.name.split('.')
            let localName = arr[arr.length - 1]
            let result = await this.ossClient.put(`${content.file.uid}.${localName}`, data);
            this.form.varLocalName = content.file.name
            this.form.varExt = localName
            this.deleteFileName = this.form.varFid = `${content.file.uid}.${localName}`
            this.uploadLoading.close();
        },
        uploadError () {
            this.uploadLoading.close();
        },
        /** 查询附件管理列表 */
        getList () {
            this.loading = true;
            listAttachment(this.queryParams).then(response => {
                this.attachmentList = response.data.rows;
                this.ancestors = response.data.ancestors
                this.total = response.data.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel () {
            this.open = false;
            this.$refs.upload.clearFiles()
            this.deleteFile(this.deleteFileName)
            this.reset();
        },
        // 表单重置
        reset () {
            this.form = {
                id: undefined,
                varName: '', // 附件名称  （必填）
                varFid: '',  // 文件id  （必填）
                varType: '', // 附件类型
                varLocalName: '', // 原始名称   （必填）
                varExt: '',  // 文件后缀   （必填）
                varIndustry: '' // 行业   （必填）
            };
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery () {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery () {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange (selection) {
            this.ids = selection.map(item => item.id)
            this.deleteNames = selection.map(item => item.varName)
            this.deleteFileNames = selection.map(item => item.varFid)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd () {
            this.reset();
            this.uploadDisabled = false;
            this.open = true;
            this.title = "添加课件";
        },
        preview (row) {
            let previewVarExt = row.varExt
            const regImg = ['jpg', 'png', 'bmp']
            if (row.varExt === 'mp4' || row.varExt === 'mp3' || regImg.indexOf(row.varExt) !== -1) {
                this.previewUrl = row.varUrl
                this.showPreview = true
                this.previewVarExt = previewVarExt
            } else if (row.varExt === 'pdf') {
                this.previewUrl = row.varUrl
                this.showPreview = true
                this.previewVarExt = previewVarExt
            } else {
                this.$message({
                    message: '文件预览暂未开通',
                    type: 'warning'
                });
            }
        },
        /** 修改按钮操作 */
        handleUpdate (row) {
            this.reset();
            const id = row.id || this.ids
            getAttachment(id).then(response => {
                for (const key in this.form) {
                    this.form[key] = response.data[key]
                }
                this.fileList = response.data.varUrl ? [{ name: response.data.varLocalName, url: response.data.varUrl, varFid: response.data.varFid }] : []
                this.uploadDisabled = this.fileList.length >= this.limitImgNumber;
                this.form.id = response.data.id
                this.beforeModifiFileName = this.form.varFid
                this.open = true;
                this.title = "修改课件";
            });
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs["form"].validate(valid => {
                if (valid) {
                    if (!this.verifyFileFormat(this.form.varExt)) {
                        return false
                    }
                    let params = Object.assign({}, this.form)
                    if (this.form.id != undefined) {
                        params.varType = this.dataFormat(this.form.varType, 'fileTypeOptions')
                        params.varIndustry = this.dataFormat(this.form.varIndustry, 'varIndustryOptions')
                        updateAttachment(params).then(response => {
                            if (response.code === 200) {
                                if (params.varFid !== this.beforeModifiFileName) {
                                    this.deleteFile(this.beforeModifiFileName, 'force')
                                }
                                this.beforeModifiFileName = ''
                                this.msgSuccess("修改成功");
                                this.$refs.upload.clearFiles()
                                this.open = false;
                                this.getList();
                            }
                        });
                    } else {
                        addAttachment(params).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess("新增成功");
                                this.$refs.upload.clearFiles()
                                this.open = false;
                                this.getList();
                            }
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete (row) {
            const ids = row.id || this.ids;
            let deleteFileNames = []
            if (row.varFid) {
                deleteFileNames[0] = row.varFid
            } else {
                deleteFileNames = this.deleteFileNames
            }
            const names = row.varName || this.deleteNames.join('，')
            this.$confirm('是否确认删除课件名为"' + names + '"的数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return delAttachment(ids);
            }).then(() => {
                deleteFileNames.forEach(item => {
                    this.deleteFile(item)
                })
                this.getList();
                this.msgSuccess("删除成功");
            }).catch(function () { });
        },
        /** 导出按钮操作 */
        handleExport () {
            const queryParams = this.queryParams;
            this.$confirm('是否确认导出所有附件管理数据项?', "警告", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(function () {
                return exportAttachment(queryParams);
            }).then(response => {
                this.download(response.msg);
            }).catch(function () { });
        },
        deleteFile (fileName, force) {
            if (!fileName) return
            if (this.form.id && !force) {
                if (this.beforeModifiFileName !== fileName) {
                    this.ossClient.delete(fileName);
                }
            } else {
                this.ossClient.delete(fileName);
            }
            this.deleteFileName = ''
        }
    }
};
</script>
<style scoped>
.tip {
    margin: 0;
    line-height: 28px;
}
</style>
